//
//  EditTravelDetailViewController.m
//  lvtu
//
//  Created by Apple on 12-6-28.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "EditTravelDetailViewController.h"
#import "DateDetailView.h"
#import "DataPartView.h"
#import "CommentDetailViewController.h"
#import "NSDate+Helper.h"
//#import "DateAddEventViewController.h"

@interface EditTravelDetailViewController ()

@end

@implementation EditTravelDetailViewController
@synthesize tripinfo;

static NSInteger DateSort(id s1, id s2, void *context)
{
    NSDate* date1 = [NSDate dateWithDateString:(NSString*)s1];
    NSTimeInterval time1 = [date1 timeIntervalSinceReferenceDate];
    NSDate* date2 = [NSDate dateWithDateString:(NSString*)s2];
    NSTimeInterval time2 = [date2 timeIntervalSinceReferenceDate];
    
    if (time1 < time2)
        return NSOrderedDescending;
    else if (time1 > time2)
        return NSOrderedAscending;
    else
        return NSOrderedSame;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithTravel:(TripInfo*) info;
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.tripinfo = info;
        dateBeforeChange = tripinfo.starttime;
        delEventArray = [[NSMutableArray alloc] init];
        
        NSArray* keyArray = [tripinfo.datedic allKeys];
        for (NSString* key in keyArray) {
            NSArray* eventArray = [tripinfo.datedic objectForKey:key];
            for (PlaceInfo* placeInfo in eventArray) {
                [delEventArray addObject:placeInfo];
            }
        }
        
        isDateChange = NO;
        isNeedDisPlay = NO;
    }
    return self;
}

- (void)dealloc
{
    [tripinfo release];
    [delEventArray release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [tempLabel setText:@"基本信息"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    
    UIImage* backImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* leftbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftbutton.frame = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
    [leftbutton setBackgroundImage:backImage forState:UIControlStateNormal];
    [leftbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [leftbutton addTarget:self action:@selector(backButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    [backButtonItem release];
    
    UIImage* editImage = [UIImage imageNamed:@"btn_finish_normal.png"];
    UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightbutton.frame = CGRectMake(0, 0, editImage.size.width, editImage.size.height);
    [rightbutton setBackgroundImage:editImage forState:UIControlStateNormal];
    [rightbutton setBackgroundImage:[UIImage imageNamed:@"btn_finish_press.png"] forState:UIControlStateHighlighted];
    [rightbutton addTarget:self action:@selector(editButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* editButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightbutton];
    self.navigationItem.rightBarButtonItem = editButtonItem;
    [editButtonItem release];
	// Do any additional setup after loading the view.
    
    backgroundScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    backgroundScrollView.backgroundColor = [UIColor clearColor];
    backgroundScrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height+240);
    backgroundScrollView.pagingEnabled = NO;
    backgroundScrollView.scrollEnabled = YES;
    backgroundScrollView.clipsToBounds = YES;
    backgroundScrollView.scrollsToTop = YES;
    backgroundScrollView.showsVerticalScrollIndicator = NO;
    backgroundScrollView.showsHorizontalScrollIndicator = NO;
//    backgroundScrollView.delegate = self;
    [self.view addSubview:backgroundScrollView];
    
    _newHeadPic = [[EGOImageView alloc] initWithFrame:CGRectMake(35, 30, 250, 50)];
//    [_newHeadPic setImage:[UIImage imageNamed:@"bg_trip_default.png"]];
    if (tripinfo.coverurl && ![tripinfo.coverurl isEqualToString:@""]) {
        [_newHeadPic setImageURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.wxlvtu.com/img.php?filename=%@",tripinfo.coverurl]]];
    }
    else {
        [_newHeadPic setImage:[UIImage imageNamed:@"bg_trip_default.png"]];
    }
    [backgroundScrollView addSubview:_newHeadPic];
    
    UIControl* temp = [[UIControl alloc] initWithFrame:_newHeadPic.frame];
    [temp addTarget:self action:@selector(snapPicButtonPress) forControlEvents:UIControlEventTouchUpInside];
    [backgroundScrollView addSubview:temp];
    [temp release];
    
    UILabel* tripLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 85, 100, 20)];
    tripLabel.text = @"点击修改图片";
    tripLabel.font = [UIFont systemFontOfSize:10];
    tripLabel.textColor = [UIColor grayColor]; 
    tripLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:tripLabel];
    [tripLabel release];
    
    UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 100, 100, 20)];
    titleLabel.text = @"设置标题:";
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:titleLabel];
    [titleLabel release];
    
    UIImage* TextFieldImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_imput.png" ofType:nil]];
    nameTextField = [[UITextField alloc] init];
    [nameTextField setFrame:CGRectMake(35, 120, 250, 40)];
    [nameTextField setBackground:TextFieldImage];
    nameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [nameTextField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [nameTextField setReturnKeyType:UIReturnKeyDefault];
    [nameTextField setFont:[UIFont boldSystemFontOfSize:12]];
    [nameTextField setDelegate:self];
    [nameTextField setTextColor:[UIColor grayColor]];
    [nameTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [nameTextField setClipsToBounds:YES];
    [nameTextField setText:tripinfo.name];
    [backgroundScrollView addSubview:nameTextField];
    [nameTextField release];
    
    UILabel* dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 165, 100, 20)];
    dateLabel.text = @"设置时间:";
    dateLabel.font = [UIFont systemFontOfSize:12];
    dateLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:dateLabel];
    [dateLabel release];
    
    UIImageView* dateInputView = [[UIImageView alloc] initWithFrame:CGRectMake(35, 185, 250, 40)];
    dateInputView.backgroundColor = [UIColor colorWithRed:227/255.0 green:227/255.0 blue:227/255.0 alpha:1.0];
    dateInputView.image = [UIImage imageNamed:@"bg_imput.png"];
    dateInputView.userInteractionEnabled = YES;
    [backgroundScrollView addSubview:dateInputView];
    [dateInputView release];
    
    UIButton* datebutton = [UIButton buttonWithType:UIButtonTypeCustom];
	datebutton.frame = CGRectMake(0, 0, 253, 40);
    [datebutton setBackgroundColor:[UIColor clearColor]];
	[datebutton addTarget:self action:@selector(dateSelectButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[dateInputView addSubview:datebutton];
    
    dateShowLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 140, 20)];
    dateShowLabel.backgroundColor = [UIColor clearColor];
    dateShowLabel.font = [UIFont boldSystemFontOfSize:22.0];
    dateShowLabel.textColor = [UIColor colorWithRed:255/255.0 green:85/255.0 blue:0/255.0 alpha:1.0];
    
//    NSDate *today = [NSDate date];
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    dateShowLabel.text = [NSString stringWithFormat:@"%@",tripinfo.starttime];//[dateFormatter stringFromDate:today]];
    [dateInputView addSubview:dateShowLabel];
//    [dateFormatter release];
    
    UILabel* detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 230, 100, 20)];
    detailLabel.text = @"备注:";
    detailLabel.font = [UIFont systemFontOfSize:12];
    detailLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:detailLabel];
    [detailLabel release];
    
    UIImage* detailTextFieldImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_imput.png" ofType:nil]];
    UIImage* stretchImg = [detailTextFieldImage stretchableImageWithLeftCapWidth:30 topCapHeight:20];
    detailTestField = [[UITextField alloc] init];
    [detailTestField setFrame:CGRectMake(35, 255, 250, 100)];
    [detailTestField setBackground:stretchImg];
    [detailTestField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [detailTestField setReturnKeyType:UIReturnKeyDone];
    [detailTestField setFont:[UIFont boldSystemFontOfSize:12]];
    [detailTestField setDelegate:self];
    [detailTestField setTextColor:[UIColor grayColor]];
    [detailTestField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [detailTestField setClipsToBounds:YES];
    [detailTestField setText:tripinfo.detail];
    [backgroundScrollView addSubview:detailTestField];
    [detailTestField release];
    
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
	button.frame = CGRectMake(220, 10, 20, 20);
    [button setBackgroundImage:[UIImage imageNamed:@"btn_unfold_normal.png"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"btn_unfold_press.png"] forState:UIControlStateHighlighted];
	[button addTarget:self action:@selector(dateSelectButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[dateInputView addSubview:button];
    
    //创建页脚button
//    UIView* footSpinnerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 288, 40)];
    UIButton* footButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [footButton setFrame:CGRectMake(100, 260, 120, 40)];
    [footButton setBackgroundImage:[UIImage imageNamed:@"btn_done_normal.png"] forState:UIControlStateNormal];
    [footButton setBackgroundImage:[UIImage imageNamed:@"btn_done_press.png"] forState:UIControlStateHighlighted];
	[footButton setTitle:@"编辑事件" forState:UIControlStateNormal];
    footButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
	[footButton addTarget:self action:@selector(nextButtonPressed) forControlEvents:UIControlEventTouchUpInside];
//    [backgroundScrollView addSubview:footButton];
//    m_tableView.tableFooterView = footSpinnerView;
    
    isPicSelect = NO;
    
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(cellClick:)
               name:@"cellclick"
             object:nil];
}

- (void)viewDidUnload
{
    if (eventEditController) {
        [eventEditController release];
    }
    [baseAlert release];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cellclick" object:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (void)viewWillAppear:(BOOL)animated
{
    [DataSource shareInstance].isEdit = YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)backButtonPress:(id)sender
{
    [self.navigationController popViewControllerAnimated:NO];
    //    [self removeFromParentViewController];
}

- (void)editButtonPress:(id)sender
{
    if ([nameTextField.text isEqualToString:@""]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"旅途名称不能为空~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
        return;
    }
    NSString* Path;
    NSDictionary* info;
    NSDate* date = [NSDate dateWithDateString:dateShowLabel.text] ;
    NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
    timeInterval += ([tripinfo.datedic count]-1)*24*60*60;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateString = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
    [dateFormatter release];
    
    if (isPicSelect) {
        Path = [NSString stringWithFormat:@"%@/%@",[[DataSource shareInstance] file_getAppCachePath],@"tripCover.jpg"];
        info = [[NSDictionary alloc] initWithObjectsAndKeys:tripinfo.travellineid,@"c_travel_line_id",dateShowLabel.text,@"start_time",dateString,@"end_time",@"1",@"c_from_city_id",nameTextField.text,@"name",Path,@"cover_image",detailTestField.text,@"detail",nil];
    }
    else {
        info = [[NSDictionary alloc] initWithObjectsAndKeys:tripinfo.travellineid,@"c_travel_line_id",dateShowLabel.text,@"start_time",dateString,@"end_time",@"1",@"c_from_city_id",nameTextField.text,@"name",detailTestField.text,@"detail",nil];
    }
    
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = TRAVELEDITLINE;
    msg.ui_delegate = self; 
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=do_edit_line" postInfo:info userInfo:msg];
    
    baseAlert = [[UIAlertView alloc] initWithTitle:@"正在发布..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [baseAlert show];
    
    UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    aiv.center = CGPointMake(baseAlert.bounds.size.width/2.0f, baseAlert.bounds.size.height-40.0f);
    [aiv startAnimating];
    [baseAlert addSubview:aiv];
    [aiv release];
}

- (void)dateSelectButtonPressed:(id)sender
{ 
    if (backgroudImageView) {
        return;
    }
    backgroudImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 163, 320, 47)];
    backgroudImageView.image = [UIImage imageNamed:@"bg_system_title.png"];
    backgroudImageView.userInteractionEnabled = YES;
    [self.view addSubview:backgroudImageView];
    
    UIButton* okbutton = [UIButton buttonWithType:UIButtonTypeCustom];
	okbutton.frame = CGRectMake(245, 8, 68, 34);
    [okbutton setBackgroundImage:[UIImage imageNamed:@"btn_system_normal.png"] forState:UIControlStateNormal];
    [okbutton setBackgroundImage:[UIImage imageNamed:@"btn_system_press.png"] forState:UIControlStateHighlighted];
	[okbutton setTitle:@"确定" forState:UIControlStateNormal];
    okbutton.titleLabel.font = [UIFont systemFontOfSize:14.0];
	[okbutton addTarget:self action:@selector(okButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroudImageView addSubview:okbutton];
    
    UIButton* cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
	cancelButton.frame = CGRectMake(10, 8, 68, 34);
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"btn_system_normal.png"] forState:UIControlStateNormal];
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"btn_system_press.png"] forState:UIControlStateHighlighted];
	[cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
	[cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroudImageView addSubview:cancelButton];
    
    datePickerView = [[UIDatePicker alloc] initWithFrame:CGRectZero];
	datePickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
	datePickerView.datePickerMode = UIDatePickerModeDate;
	
	// note we are using CGRectZero for the dimensions of our picker view,
	// this is because picker views have a built in optimum size,
	// you just need to set the correct origin in your view.
	//
	// position the picker at the bottom
	datePickerView.frame = CGRectMake(0.0,210,320,200);
	
	// add this picker to our view controller, initially hidden
	datePickerView.hidden = NO;
    NSDate *date = [NSDate dateWithDateString:tripinfo.starttime];
    [datePickerView addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
	datePickerView.date = date;
	[self.view addSubview:datePickerView];
}

-(void)dateChanged:(id)sender
{
    UIDatePicker* datePicker = (UIDatePicker*)sender;
    // report the selection to the UI label
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    dateShowLabel.text = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:datePicker.date]];
    [dateFormatter release];
}

- (void)okButtonPressed:(id)sender
{ 
    if (!backgroudImageView) {
        return;
    }
    if ([backgroudImageView isDescendantOfView:self.view]) {
        [backgroudImageView removeFromSuperview];
        [backgroudImageView release];backgroudImageView= nil;
    }
    if ([datePickerView isDescendantOfView:self.view]) {
        [datePickerView removeFromSuperview];
        [datePickerView release];datePickerView = nil;
    }
//    [backgroundScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    if (![dateBeforeChange isEqualToString:dateShowLabel.text]) {
        isDateChange = YES;
    }
}

- (void)cancelButtonPressed:(id)sender
{
    if (!backgroudImageView) {
        return;
    }
    if ([backgroudImageView isDescendantOfView:self.view]) {
        [backgroudImageView removeFromSuperview];
        [backgroudImageView release];backgroudImageView= nil;
    }
    if ([datePickerView isDescendantOfView:self.view]) {
        [datePickerView removeFromSuperview];
        [datePickerView release];datePickerView = nil;
    }
//    NSDate *today = [NSDate date];
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    dateShowLabel.text = [NSString stringWithFormat:@"%@",dateBeforeChange];
}
#pragma 
#pragma mark   user  action
- (void) snapPicButtonPress
{
    UIActionSheet *menu  = nil;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        menu = [[UIActionSheet alloc]
                initWithTitle: nil
                delegate:self
                cancelButtonTitle:@"Cancel"
                destructiveButtonTitle:nil
                otherButtonTitles:@"从相册中选", @"拍照", nil];
    }
    else
    {
        menu = [[UIActionSheet alloc]
                initWithTitle: nil
                delegate:self
                cancelButtonTitle:@"Cancel"
                destructiveButtonTitle:nil
                otherButtonTitles:@"从相册中选", nil];
    }
    
    [menu showInView:self.view];
    [menu release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    printf("User Pressed Button %d\n", buttonIndex + 1);
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        if(buttonIndex == 0)
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            ipc.delegate = self;
            ipc.allowsEditing = YES; //3.0
            
            [self presentModalViewController:ipc animated:YES];	
        }
        else if(buttonIndex == 1)
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypeCamera;
            
            ipc.delegate = self;
            ipc.allowsEditing = YES; //3.0
            [self presentModalViewController:ipc animated:YES];	
        }
    }
    else
    {
        if(buttonIndex == 0)
        {
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            ipc.delegate = self;
            ipc.allowsEditing = YES; //3.0
            
            [self presentModalViewController:ipc animated:YES];	
        }
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	UIImage* image = (UIImage*)[info objectForKey:@"UIImagePickerControllerEditedImage"];
	[self dismissModalViewControllerAnimated:YES];
	[picker release];
    _newHeadPic.image = image;
    
    NSString* Path = [NSString stringWithFormat:@"%@/%@",[[DataSource shareInstance] file_getAppCachePath],@"tripCover.jpg"];
    [UIImageJPEGRepresentation(image, 0.4f) writeToFile:Path atomically:YES];
    isPicSelect = YES;
}


- (void)touchUpInsideDetailCell:(NSString*)dateIndexText Index:(NSInteger)index Detail:(NSString*)detailIndexText button:(NSInteger)buttontype ementType:(ElementType)type
{
//    if (buttontype == 0) {
//        [[DataSource shareInstance] creatNewDateEdit:[detailIndexText substringToIndex:[detailIndexText rangeOfString:@"，"].location]];
//        [[DataSource shareInstance] setDatePartEdit:[NSString stringWithFormat:@"%d",type]]; 
//        
//        DateAddEventViewController* dateAddEventViewController = [[DateAddEventViewController alloc] init];
//        dateAddEventViewController.isTripEdit = YES;
//        [dateAddEventViewController setDateContent:dateIndexText date:[NSString stringWithFormat:@"%@",detailIndexText]];
//        
//        NSArray* dictArray = [tripinfo.datedic allKeys];
//        NSArray* sortArray = [dictArray sortedArrayUsingFunction:DateSort context:NULL];
//        NSDictionary* datePartDict = [tripinfo.datedic objectForKey:[sortArray objectAtIndex:[sortArray count]-index-1]];
//        
//        NSDictionary* eventDict = [datePartDict objectForKey:[NSString stringWithFormat:@"%d",type]];
//        [dateAddEventViewController updateAllEventByEdit:eventDict];
//        //CustomTabBarController* tabarController = (CustomTabBarController*)self.tabBarController;
//        [self.navigationController pushViewController:dateAddEventViewController animated:YES];
////        [dateAddEventViewController release];
//    }
//    else {
//        NSArray* dictArray = [tripinfo.datedic allKeys];
//        NSArray* sortArray = [dictArray sortedArrayUsingFunction:DateSort context:NULL];
//        NSDictionary* datePartDict = [tripinfo.datedic objectForKey:[sortArray objectAtIndex:[sortArray count]-index-1]];
//        
//        NSDictionary* eventDict = [datePartDict objectForKey:[NSString stringWithFormat:@"%d",type]];
//        
//        EventViewController* eventViewController = [[EventViewController alloc] initWithType:YES edit:YES];
//        eventViewController.delegate = self;
//        [eventViewController.m_ShowAry addObjectsFromArray:[eventDict objectForKey:@"list"]];
//        [self.navigationController pushViewController:eventViewController animated:YES];
//        [eventViewController release];
//    }
}

- (void)nextButtonPressed
{
//    NSString* newDate;
//    if ([tripinfo.datedic count] > 0) {
//        NSArray* dictArray = [tripinfo.datedic allKeys];
//        NSArray* sortArray = [dictArray sortedArrayUsingFunction:DateSort context:NULL];
//        
//        NSDate* date = [NSDate dateWithDateString:[sortArray objectAtIndex:0]];
//        NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
//        timeInterval += 24*60*60;
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//        newDate = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
//    }
//    else {
//        NSDate *today = [NSDate date];
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//        newDate = [dateFormatter stringFromDate:today];
//    }
    
    dateIndex = 1;
    
    NSArray* keyArray = [[DataSource shareInstance].editTripInfo.datedic allKeys];
    BOOL isFind = NO;
    for (NSString* key in keyArray) {
        if ([key isEqualToString:tripinfo.starttime]) {
            isFind = YES;
            break;
        }
    }
    if (isFind) {
        [[DataSource shareInstance] setDate:tripinfo.starttime];
    }
    else{
        
        [[DataSource shareInstance] creatNextDate:tripinfo.starttime];
    }
    NSArray* eventArray = [[DataSource shareInstance] getCurrentEvent];
    for (PlaceInfo* info in eventArray) {
        for (CityInfo* city in [DataSource shareInstance].cityArray) {
            if ([info.cityid isEqualToString:city.cityid]) {
                [DataSource shareInstance].defaultCityInfo = city;
                break;
            }
        }
        break;
    }
    
    eventEditController = [[EventEditViewController alloc] init];
    [eventEditController setCurrentInfo:dateIndex];
    eventEditController.delegate = self;
    [self.navigationController pushViewController:eventEditController animated:YES];
    
//    [[DataSource shareInstance] creatNewDateEdit:newDate];
    
//    [[DataSource shareInstance] setDatePartEdit:[NSString stringWithFormat:@"%d",type]]; 
//    
//    DateAddEventViewController* dateAddEventViewController = [[DateAddEventViewController alloc] init];
//    dateAddEventViewController.isTripEdit = YES;
//    [dateAddEventViewController setDateContent:dateIndexText date:[NSString stringWithFormat:@"%@",detailIndexText]];
//    
//    
//    NSDictionary* datePartDict = [tripinfo.datedic objectForKey:[sortArray objectAtIndex:[sortArray count]-index-1]];
//    
//    NSDictionary* eventDict = [datePartDict objectForKey:[NSString stringWithFormat:@"%d",type]];
//    [dateAddEventViewController updateAllEventByEdit:eventDict];
//    //CustomTabBarController* tabarController = (CustomTabBarController*)self.tabBarController;
//    [self.navigationController pushViewController:dateAddEventViewController animated:YES];
}

- (void)touchPreDayButton
{
    dateIndex--;
    NSDate* date = [NSDate dateWithDateString:tripinfo.starttime] ;
    NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
    timeInterval += 24*60*60*(dateIndex-1);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateString = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
    [dateFormatter release];
    
    [eventEditController.navigationController popViewControllerAnimated:NO];
    [[DataSource shareInstance] setDate:dateString];
    
    NSArray* eventArray = [[DataSource shareInstance] getCurrentEvent];
    for (PlaceInfo* info in eventArray) {
        for (CityInfo* city in [DataSource shareInstance].cityArray) {
            if ([info.cityid isEqualToString:city.cityid]) {
                [DataSource shareInstance].defaultCityInfo = city;
                break;
            }
        }
        break;
    }
    eventEditController = [[EventEditViewController alloc] init];
    [eventEditController setCurrentInfo:dateIndex];
    eventEditController.delegate = self;
    
    CATransition *transition = [CATransition animation];
    transition.duration = 0.2;
    //    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromLeft;
    transition.delegate = self;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController pushViewController:eventEditController animated:NO];
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    [eventEditController release];
}

- (void)touchNextDayButton
{
    if ([[[DataSource shareInstance] getCurrentEvent] count] == 0) {
        UIAlertView* tempAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"今天还未添加任何内容哟~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [tempAlert show];
        [tempAlert release];
        return;
    }
    dateIndex++;
    NSDate* date = [NSDate dateWithDateString:tripinfo.starttime] ;
    NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
    timeInterval += 24*60*60*(dateIndex-1);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateString = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
    [dateFormatter release];
    
    [eventEditController.navigationController popViewControllerAnimated:NO];
    NSArray* keyArray = [[DataSource shareInstance].editTripInfo.datedic allKeys];
    BOOL isFind = NO;
    for (NSString* key in keyArray) {
        if ([key isEqualToString:dateString]) {
            isFind = YES;
            break;
        }
    }
    if (isFind) {
        [[DataSource shareInstance] setDate:dateString];
    }
    else{
        
        [[DataSource shareInstance] creatNextDate:dateString];
    }
    
    NSArray* eventArray = [[DataSource shareInstance] getCurrentEvent];
    for (PlaceInfo* info in eventArray) {
        for (CityInfo* city in [DataSource shareInstance].cityArray) {
            if ([info.cityid isEqualToString:city.cityid]) {
                [DataSource shareInstance].defaultCityInfo = city;
                break;
            }
        }
        break;
    }
    eventEditController = [[EventEditViewController alloc] init];
    [eventEditController setCurrentInfo:dateIndex];
    eventEditController.delegate = self;
    [self.navigationController pushViewController:eventEditController animated:YES];
}

- (void)cellClick:(NSNotification*)note
{
    
}

- (BOOL)addEvent:(PlaceInfo*)info type:(ElementType)type
{
    return YES;
}

- (BOOL)delEvent:(PlaceInfo*)info type:(ElementType)type
{
    return YES;
}

#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [nameTextField resignFirstResponder];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    
    if ([string isEqualToString:@"\n"])
    {//按下return键
        //这里隐藏键盘，不做任何处理
        [textField resignFirstResponder];
        //        [self willLoginWeibo];
        return NO;
    }
    else
    {
        return YES;
    }
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == nameTextField) {
        [nameTextField setText:@""];
        [nameTextField setPlaceholder:@""];
        [nameTextField setTextColor:[UIColor grayColor]];
    }
    else if (textField == detailTestField)
    {
        [detailTestField setText:@""];
        [detailTestField setPlaceholder:@""];
        [detailTestField setTextColor:[UIColor grayColor]];
    }
    
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0 && alertView.tag != 2001) {
        [self.navigationController popViewControllerAnimated:NO];
    }
}

#pragma -mark DataSourceDelegate

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: TRAVELEDITLINE]) {
        NSDictionary* info;
        CoreMsg* msg = [[CoreMsg alloc] init];
        if ([DataSource shareInstance].isEditDataChanged) {
            NSMutableArray* array = [[NSMutableArray alloc] init];
            for (id shopinfo in delEventArray) {
                if ([shopinfo isKindOfClass:[PlaceInfo class]]) {
                    [array addObject:((PlaceInfo*)shopinfo).eventid];
                }
                else {
                    [array addObject:[((NSDictionary*)shopinfo) objectForKey:@"c_travel_event_id"]];
                }
            }
            NSMutableString* jsons = [NSMutableString stringWithString:@"["];
            for (int i = 0; i < [array count]; i++) {
                if (i > 0) {
                    [jsons appendString:[NSString stringWithFormat:@",\"%@\"",[array objectAtIndex:i]]];
                }
                else {
                    [jsons appendString:[NSString stringWithFormat:@"\"%@\"",[array objectAtIndex:i]]];
                }
            }
            [jsons appendString:@"]"];
            info = [[NSDictionary alloc] initWithObjectsAndKeys:tripinfo.travellineid,@"c_travel_line_id",jsons,@"json_data",nil];
            msg.data = DELEDITEVENTLIST;
            msg.ui_delegate = self;
            [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=do_delete_event_list" postInfo:info userInfo:msg];
            [array removeAllObjects];
            return;
        }
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"修改成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
    else if ([coreMsg.data isEqual: DELEDITEVENTLIST])
    {
        NSMutableString* jsons = [[DataSource shareInstance] newTripJSONString];
        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:tripinfo.travellineid,@"c_travel_line_id",jsons,@"json_data",nil];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = CREATEVENTLIST;
        msg.ui_delegate = self;
        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=do_create_event_list_new" postInfo:info userInfo:msg];
        [[DataSource shareInstance].editTripInfo.datedic removeAllObjects];
    }
    else if((coreMsg.data = CREATEVENTLIST)){
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"修改成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: TRAVELEDITLINE]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"修改失败啦！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

@end
